package com.wang.users.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wang.common.pojo.BasePojoEnum;
import com.wang.common.util.BeanUtil;
import com.wang.common.util.DateUtil;
import com.wang.common.util.RegexUtil;
import com.wang.users.mapper.AtUsersScheduleMapper;
import com.wang.users.pojo.AtUsersSchedule;
import com.wang.users.pojo.AtUsersScheduleEnum;
import com.wang.users.pojo.AtUsersScheduleQuery;
import com.wang.users.pojo.AtUsersScheduleStaff;
import com.wang.users.pojo.AtUsersScheduleStaffEnum;
import com.wang.users.pojo.AtUsersScheduleStaffQuery;
import com.wang.users.service.AtUsersScheduleService;
import com.wang.users.service.AtUsersScheduleStaffService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 针对表【at_demo_dynasty(示例_朝代表)】的数据库操作Service实现
 *
 * @author ZjxMi
 */
@Service
@Log4j2
public class AtUsersScheduleServiceImpl extends ServiceImpl<AtUsersScheduleMapper, AtUsersSchedule>
        implements AtUsersScheduleService {

    @Autowired
    private BeanUtil beanUtil;
    @Autowired
    private RegexUtil regexUtil;
    @Autowired
    private DateUtil dateUtil;
    @Autowired
    private AtUsersScheduleStaffService usersScheduleStaffService;

    /**
     * 生成单号
     * @return
     */
    private String proccedRandSn(){
        String timeStr = this.dateUtil.dateToStr(new Date(), DateUtil.DATETIME_ALL_FORMAT);
        String randStr = this.regexUtil.randStr("2", 5);
        return AtUsersScheduleQuery.NO_PRE_STR + timeStr + randStr;
    }

    /**
     * model2: jsp --> servlet -->service --> dao --> db, 我们自己封装了一个 PageInfoUtil;
     * MybatisPlus: 不再需要调用 PageInfoUtil,老代码改造的时候是为了整合代码,如果没有老代码,直接写的新代码,采用下面的方式来搞
     *
     * @param page
     * @param query 查询对象
     * @return
     */
    @Override
    public List<AtUsersSchedule> findList(IPage<AtUsersSchedule> page, AtUsersScheduleQuery query) {
        if (page != null) {
            return this.baseMapper.findList(page, query);
        }
        return this.baseMapper.findList(query);
    }

    @Override
    public AtUsersSchedule findOne(AtUsersScheduleQuery query) {
        AtUsersSchedule one = this.baseMapper.findOne(query);
        if (Objects.nonNull(one)) {
            /* 查询考察人员和陪同人员 */
            AtUsersScheduleStaffQuery param = new AtUsersScheduleStaffQuery();
            AtUsersScheduleStaff entity = param.getEntity();
            entity.setSchedueId(one.getId());
            entity.setStaffType(AtUsersScheduleStaffEnum.STAFFTYPE_ZHUCHIREN.getCode());
            List<AtUsersScheduleStaff> kaoChaList = this.usersScheduleStaffService.findList(null, param);
            one.setStaffTypeZcrList(kaoChaList);

            entity.setStaffType(AtUsersScheduleStaffEnum.STAFFTYPE_CANJIAREN.getCode());
            List<AtUsersScheduleStaff> peitongList = this.usersScheduleStaffService.findList(null, param);
            one.setStaffTypeCanjiaList(peitongList);
        }
        return one;
    }

    @Override
    public int updateBatch(AtUsersScheduleQuery query) {
        return this.baseMapper.updateBatch(query);
    }

    @Override
    public int deleteBatch(AtUsersScheduleQuery query) {
        return this.baseMapper.deleteBatch(query);
    }

    /**
     * 对数据额外处理(非用户填写的数据)
     * @param entity
     */
    private void proccedUpdateData(AtUsersSchedule entity){
        if (Objects.isNull(entity.getCreateTime())) {
            entity.setCreateTime(new Date());
        }
        entity.setUpdateTime(new Date());
        /* 判断对象是否为空 */
        if (Objects.isNull(entity.getPubTime())) {
            entity.setPubTime(new Date());
        }
    }

    @Override
    public boolean save(AtUsersSchedule entity) {
        this.proccedUpdateData(entity);
        /* 新增加的记录默认未删除 */
        entity.setDelFlag(BasePojoEnum.DELFLAG_NO.getCode());
        entity.setStatus(AtUsersScheduleEnum.STATUSNEW_YLR.getCode());
        boolean dbSave = super.save(entity);
        if (dbSave) {
            /* 删除所有用户数据 */
            AtUsersScheduleStaffQuery paramStaffQuery = new AtUsersScheduleStaffQuery();
            if (Objects.nonNull(entity.getStaffTypeZcr()) && entity.getStaffTypeZcr().length > 0) {
                AtUsersScheduleStaff staffEntity = paramStaffQuery.getEntity();
                staffEntity.setSchedueId(entity.getId());
                staffEntity.setStaffType(AtUsersScheduleStaffEnum.STAFFTYPE_ZHUCHIREN.getCode());
                int dbRes = this.usersScheduleStaffService.deleteBatch(paramStaffQuery);
                log.info("==删除结果;schedueId:{},条数:{}==", entity.getId(), dbRes);

                /* 添加人员信息 */
                String[] staffTypeKaocha = entity.getStaffTypeZcr();
                for (String dataTemp : staffTypeKaocha) {
                    AtUsersScheduleStaff staffEntityTemp = new AtUsersScheduleStaff();
                    staffEntityTemp.setSchedueId(entity.getId());
                    staffEntityTemp.setUsersId(dataTemp);
                    staffEntityTemp.setStaffType(AtUsersScheduleStaffEnum.STAFFTYPE_ZHUCHIREN.getCode());
                    this.usersScheduleStaffService.save(staffEntityTemp);
                }
            }

            if (Objects.nonNull(entity.getStaffTypeCanjia()) && entity.getStaffTypeCanjia().length > 0) {
                /* 删除所有用户数据 */
                AtUsersScheduleStaff staffEntity = paramStaffQuery.getEntity();
                staffEntity.setSchedueId(entity.getId());
                staffEntity.setStaffType(AtUsersScheduleStaffEnum.STAFFTYPE_CANJIAREN.getCode());
                int dbRes = this.usersScheduleStaffService.deleteBatch(paramStaffQuery);
                log.info("==删除结果;schedueId:{},条数:{}==", entity.getId(), dbRes);

                String[] staffTypePeitong = entity.getStaffTypeCanjia();
                for (String dataTemp : staffTypePeitong) {
                    AtUsersScheduleStaff staffEntityTemp = new AtUsersScheduleStaff();
                    staffEntityTemp.setSchedueId(entity.getId());
                    staffEntityTemp.setUsersId(dataTemp);
                    staffEntityTemp.setStaffType(AtUsersScheduleStaffEnum.STAFFTYPE_CANJIAREN.getCode());
                    this.usersScheduleStaffService.save(staffEntityTemp);
                }
            }
        }
        return dbSave;
    }

    @Override
    public boolean updateById(AtUsersSchedule entity) {
        /* 先根据id查询数据库的内容; */
        AtUsersScheduleQuery paramQuery = new AtUsersScheduleQuery();
        AtUsersSchedule entityParam = paramQuery.getEntity();
        entityParam.setId(entity.getId());
        /* 数据库中查询的结果 */
        AtUsersSchedule oneDbResult = this.findOne(paramQuery);
        AtUsersSchedule updateDb = new AtUsersSchedule();

        if ( (
                AtUsersScheduleEnum.STATUSNEW_SHTG.getCode().equalsIgnoreCase(entity.getStatus()) ||
                AtUsersScheduleEnum.STATUSNEW_SHBTG.getCode().equalsIgnoreCase(entity.getStatus())
            )
            && AtUsersScheduleEnum.STATUSNEW_YFB.getCode().equalsIgnoreCase(oneDbResult.getStatus())
        ) {
           /* 正在进行审核 */
           Date currDate = new Date();
           if (currDate.after(oneDbResult.getProccedEndTime())) {
               /* 已经过了审核日期,无法进行审核 */
               Assert.isTrue(false, "已经过了审核日期,无法进行审核");
           }
        }
        /*
        * 源对象和目标对象是一个类型(10个字段)
        * 源对象有5个字段有值,目标对象是10个有值
        * 把源对象中的5个字段有值,赋值到目标对象中.(覆盖)
        * */
        updateDb = (AtUsersSchedule) this.beanUtil.copy(oneDbResult, updateDb);
        updateDb = (AtUsersSchedule) this.beanUtil.copy(entity, updateDb);
        this.proccedUpdateData(updateDb);
        boolean dbSave = super.updateById(updateDb);
        if (dbSave) {
            /* 删除所有用户数据 */
            AtUsersScheduleStaffQuery paramStaffQuery = new AtUsersScheduleStaffQuery();
            if (Objects.nonNull(entity.getStaffTypeZcr()) && entity.getStaffTypeZcr().length > 0) {
                AtUsersScheduleStaff staffEntity = paramStaffQuery.getEntity();
                staffEntity.setSchedueId(entity.getId());
                staffEntity.setStaffType(AtUsersScheduleStaffEnum.STAFFTYPE_ZHUCHIREN.getCode());
                int dbRes = this.usersScheduleStaffService.deleteBatch(paramStaffQuery);
                log.info("==删除结果;schedueId:{},条数:{}==", entity.getId(), dbRes);

                /* 添加人员信息 */
                String[] staffTypeKaocha = entity.getStaffTypeZcr();
                for (String dataTemp : staffTypeKaocha) {
                    AtUsersScheduleStaff staffEntityTemp = new AtUsersScheduleStaff();
                    staffEntityTemp.setSchedueId(entity.getId());
                    staffEntityTemp.setUsersId(dataTemp);
                    staffEntityTemp.setStaffType(AtUsersScheduleStaffEnum.STAFFTYPE_ZHUCHIREN.getCode());
                    this.usersScheduleStaffService.save(staffEntityTemp);
                }
            }

            if (Objects.nonNull(entity.getStaffTypeCanjia()) && entity.getStaffTypeCanjia().length > 0) {
                /* 删除所有用户数据 */
                AtUsersScheduleStaff staffEntity = paramStaffQuery.getEntity();
                staffEntity.setSchedueId(entity.getId());
                staffEntity.setStaffType(AtUsersScheduleStaffEnum.STAFFTYPE_CANJIAREN.getCode());
                int dbRes = this.usersScheduleStaffService.deleteBatch(paramStaffQuery);
                log.info("==删除结果;schedueId:{},条数:{}==", entity.getId(), dbRes);

                String[] staffTypePeitong = entity.getStaffTypeCanjia();
                for (String dataTemp : staffTypePeitong) {
                    AtUsersScheduleStaff staffEntityTemp = new AtUsersScheduleStaff();
                    staffEntityTemp.setSchedueId(entity.getId());
                    staffEntityTemp.setUsersId(dataTemp);
                    staffEntityTemp.setStaffType(AtUsersScheduleStaffEnum.STAFFTYPE_CANJIAREN.getCode());
                    this.usersScheduleStaffService.save(staffEntityTemp);
                }
            }
        }
        return dbSave;
    }
}